<script lang="ts" setup>
import { ref, watch } from 'vue'
import * as workPlaceWeChatApi from '@/api/workPlaceWeChat'
import { timeFormat } from '@/hooks/util'
import { message } from 'ant-design-vue'
import SetWeChat from './SetWeChat.vue'
import YzmModal from './YzmModal.vue'

import QRCode from 'qrcodejs2-fix'

import { useBrandStore } from '@/store/modules/brand'

const brandStore = useBrandStore()

const setWeChatRef = ref()
const yzmModalRef = ref()

const handleChange = (value: string) => {
  console.log(`selected ${value}`)
}

const value = ref([])

const options = [...Array(25)].map((_, i) => ({ value: (i + 10).toString(36) + (i + 1) }))

//#region 微信扫码登录

const AppID = 'wxc087a218643a7b09' // 票达人CRM

let local = `http://pdr-web-v2.liangpiao.net.cn/cdx2.html` // 线上 - 重定向配置（微信扫码后，会重定向到这个地址）

if (window.location.origin.indexOf('192.168') != -1) {
  local = `http://pdr-web-v2.liangpiao.net.cn/cdx1.html?id=123&name=dnfdnf` // 开发 - 重定向配置（微信扫码后，会重定向到这个地址）
  // local = `http://pdr-web.liangpiao.net.cn/cdx1.html` // 测试环境 - 重定向配置（微信扫码后，会重定向到这个地址）
}

local = encodeURIComponent(local)

let url = local

let wxLoginContainer = ref()

const script = document.createElement('script')
script.src = 'http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js'
script.async = true // 设置为异步加载，这样不会阻塞页面的其他资源加载

// 当脚本加载完成后，执行回调函数
script.onload = () => {
  // 检查 WxLogin 函数是否存在，以确保脚本已正确加载
  if (typeof WxLogin === 'function' && wxLoginContainer.value) {
    // console.log('wxLoginContainer=', wxLoginContainer.value.id)

    // 初始化微信登录按钮
    new WxLogin({
      id: wxLoginContainer.value.id, // 容器的ID
      appid: AppID,
      scope: 'snsapi_login',
      redirect_uri: url,
      state: 'STATE', // 可选参数，用于防止csrf攻击
      // style: 'black', // 可选，按钮样式，默认black
      // href: '', // 可选，自定义样式链接
      href: 'data:text/css;base64,LmltcG93ZXJCb3ggLnRpdGxlIHsNCiAgICBkaXNwbGF5OiBub25lOw0KfQ0KLmltcG93ZXJCb3ggLnFyY29kZS5saWdodEJvcmRlciB7DQogICAgd2lkdGg6IDIwMHB4Ow0KfQ==',
    })
  } else {
    console.error('WxLogin function is not defined. Make sure the script is loaded correctly.')
  }
}

// 将 script 元素添加到页面的 head 或 body 中
document.head.appendChild(script)

//#endregion 微信扫码登录

const bindWeChat = async (code: string) => {
  try {
    let {
      state,
      data,
      message: msg,
    } = await workPlaceWeChatApi.addPublicWechatUserRelevancy({ code })
    if (state === 200) {
      message.success('绑定成功')
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('绑定失败，请扫码重试~')
  }
}

onMounted(() => {
  // console.log('window=', window)
  /*
    window.location.href的值是：http://192.168.110.28:3000/#/work-place/?code=081kzn100qS9rT17HI2007OmZr4kzn1d&state=STATE
    因为，URL包含哈希部分（#），所以，需要先处理这部分
    URL对象不能直接解析哈希部分后的查询字符串，因此我们需要手动提取这部分。*/
  let url = window.location.href
  const hashUrl = url.split('#')[1] // 获取#后面的部分
  const queryString = hashUrl.split('?')[1] // 获取?后面的查询字符串

  // 使用URLSearchParams对象来解析查询字符串
  const params = new URLSearchParams(queryString)
  let code = ''
  code = params.get('code') as string

  // console.log('code=', code)

  if (code) {
    bindWeChat(code)
  }

  // getList()

  // 生成二维码
  // creatQrCode()
})

const dataSource = ref([])
const columns = [
  {
    title: '头像',
    key: 'avatar',
    width: 80,
  },
  {
    title: '昵称',
    key: 'nickName',
    width: 100,
  },
  // {
  //   title: '关联时间',
  //   key: 'relevancyTime',
  //   width: 180,
  // },
  {
    title: '操作',
    key: 'action',
    fixed: 'right',
  },
]

const getList = async () => {
  try {
    let {
      state,
      data,
      message: msg,
    } = await workPlaceWeChatApi.getPublicWechatUserRelevancyList({
      currentPage: 1,
      pageSize: 100,
    })
    if (state === 200) {
      dataSource.value = data.list
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

const jieBang = async (id: any) => {
  try {
    let { state, data, message: msg } = await workPlaceWeChatApi.deleteQuotationRule({ id })
    if (state === 200) {
      message.success('解绑成功')
    } else {
      message.error(msg)
    }
  } catch (error) {
    message.error('网络请求连接失败~')
  }
}

// 生成二维码
let qrCodeUrlRef = ref()
const creatQrCode = () => {
  let qrcode = new QRCode(qrCodeUrlRef.value, {
    text: 'http://pdr-h5-v2.liangpiao.net.cn/?userId=123', // 需要转换为二维码的内容
    width: 100,
    height: 100,
    colorDark: '#000000',
    colorLight: '#ffffff',
    correctLevel: QRCode.CorrectLevel.H,
  })
}

let theUrl = ref('')
theUrl.value = window.location.href
watch(
  theUrl,
  (newVal, oldVal) => {
    console.log('newVal=', newVal)
    // setTimeout(() => {
    //   creatQrCode()
    // }, 500)
  },
  {
    immediate: true,
  },
)

// 微信扫码关注公众号
const setWeChat = () => {
  // 二维码+列表 - 弹框
  // setWeChatRef.value.showModal()

  // 验证码的弹框
  yzmModalRef.value.showModal()
}
</script>

<template>
  <div class="setting-container">
    <a-card title="系统监控（推荐使用云感知服务）" :bordered="false">
      <template #cover>
        <div style="padding: 10px 25px">
          <a-alert v-if="brandStore.workPlace_setWeChat" type="success" show-icon>
            <template #message>
              云感知服务：微信接收异常通知，可多微信扫码关注
              <a @click="setWeChat">立即设置</a>
            </template>
          </a-alert>
        </div>

        <div class="card-cover">
          <div class="select">
            <div class="select_1">
              <a-select
                v-model:value="value"
                mode="tags"
                disabled
                style="width: 100%"
                placeholder="选择平台账号"
                :options="options"
                @change="handleChange"
              ></a-select>
            </div>

            <div class="select_2">
              <a-select
                v-model:value="value"
                mode="tags"
                disabled
                style="width: 100%"
                placeholder="分组"
                :options="options"
                @change="handleChange"
              ></a-select>
            </div>
          </div>

          <div class="btn">
            <div class="btn_1">
              <a-button type="primary" disabled block>重启/更新客户端</a-button>
            </div>

            <div class="btn_2">
              <a-button type="primary" disabled block>检测客户端状态</a-button>
            </div>
          </div>

          <!-- 微信 - 网站应用 - 暂时停掉 -->
          <!-- <div style="height: 250px">
            <div ref="wxLoginContainer" id="wxLoginContainer"></div>
          </div> -->
          <!-- 微信 - 网站应用 - 暂时停掉 -->

          <!-- 暂替的方案 -->
          <!-- <div>
            <div style="padding: 10px 10px 0 30px">微信扫描二维码关注公众号</div>
            <div style="padding: 10px 10px 0 60px" ref="qrCodeUrlRef"></div>
          </div> -->
          <!-- 暂替的方案 -->
        </div>
      </template>
    </a-card>

    <SetWeChat ref="setWeChatRef"></SetWeChat>
    <YzmModal ref="yzmModalRef"></YzmModal>
  </div>
</template>

<style lang="less" scoped>
.hiddenText {
  display: inline-block;
  max-width: 120px;
  overflow: hidden;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
  line-height: 16px;
}

.imgBox {
  width: 50px;
  height: 50px;
  border-radius: 50%;
  overflow: hidden;

  img {
    height: 50px;
  }
}

.setting-container {
  .card-cover {
    padding: 0 25px 25px 25px;
    box-sizing: border-box;
    // display: flex;

    .select {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .select_1 {
        flex: 4;
      }

      .select_2 {
        flex: 1;
        margin-left: 10px;
      }
    }

    .btn {
      display: flex;
      align-items: center;
      justify-content: space-between;
      margin-top: 10px;
      .btn_1 {
        flex: 1;
      }

      .btn_2 {
        margin-left: 10px;
        flex: 1;
      }
    }
  }
}
</style>
